package com.hr.mes.handler;

import com.hr.mes.dto.Result;
import com.hr.mes.enums.MyExceptionEnum;
import com.hr.mes.exception.MyException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public Result handleExceptionInControllers(Exception e){
        Throwable cause = e.getCause();
        if(!ObjectUtils.isEmpty(cause)){
            cause.printStackTrace();
        }
        if(e instanceof MyException){
            MyException myException = (MyException)e;
            return new Result(myException.getMyExceptionEnum().getCode(), myException.getMyExceptionEnum().getMsg(), null);
        }else{
            return new Result(MyExceptionEnum.ERROR.getCode(), MyExceptionEnum.ERROR.getMsg(), null);
        }
    }
}
